const { Category } = require('../models');

module.exports = {
  async createCategory(ctx) {
    const { name, description } = ctx.request.body;
    if (!name) {
      ctx.throw(400, '分类名称不能为空');
    }

    // 判断是否已存在
    const exist = await Category.findOne({ where: { name } });
    if (exist) {
      ctx.throw(400, '分类名称已存在');
    }

    const category = await Category.create({ name, description });
    ctx.body = {
      code: 0,
      msg: '创建成功',
      data: category,
    };
  },

  async getCategories(ctx) {
    const categories = await Category.findAll();
    ctx.body = {
      code: 0,
      data: categories,
    };
  },

  async updateCategory(ctx) {
    const id = ctx.params.id;
    const { name, description } = ctx.request.body;

    const category = await Category.findByPk(id);
    if (!category) {
      ctx.throw(404, '分类不存在');
    }

    if (name) {
      // 检查是否重复
      const exist = await Category.findOne({ where: { name, id: { $ne: id } } });
      if (exist) {
        ctx.throw(400, '分类名称已存在');
      }
    }

    await category.update({ name, description });
    ctx.body = {
      code: 0,
      msg: '更新成功',
      data: category,
    };
  },

  async deleteCategory(ctx) {
    const id = ctx.params.id;
    const category = await Category.findByPk(id);
    if (!category) {
      ctx.throw(404, '分类不存在');
    }
    await category.destroy();
    ctx.body = {
      code: 0,
      msg: '删除成功',
    };
  },
};
